﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web;
using System.Web.Mvc;
using Api.Common;
using Newtonsoft.Json;
using AppManager.DomainModel;

namespace AppManager.Background
{
    /// <summary>
    ///     測試發送推送消息
    /// </summary>
    public class TestPushController : BaseController
    {
        public ActionResult AddProject()
        {
            ViewBag.isNew = true;
            Th.PageHeaderCrumbs = new List<string> { "添加項目信息", "Home", "推送到PushManager(新)" };
            return View();
        }

        public ActionResult AddMessage()
        {
            Th.PageHeaderCrumbs = new List<string> { "發送推送消息", "Home", "推送到PushManager(新)" };
            return View();
        }

        public ActionResult AddProject2()
        {
            ViewBag.isNew = false;
            Th.PageHeaderCrumbs = new List<string> { "添加項目信息", "Home", "推送到AppMsgPush(舊)" };
            return View("AddProject");
        }

        public ActionResult AddMessage2()
        {
            Th.PageHeaderCrumbs = new List<string> { "發送推送消息", "Home", "推送到AppMsgPush(舊)" };
            return View();
        }

        [HttpPost]
        public ActionResult AddProject(AddProjectModel model)
        {
            ViewBag.isNew = true;
            Th.PageHeaderCrumbs = new List<string> { "添加項目信息", "Home", "推送到PushManager(新)" };

            if (!ModelState.IsValid || model == null)
            {
                ViewBag.HasModelError = true;
                return View(model);
            }
            string url = model.ServerUrl;

            var nvc = new NameValueCollection();
            nvc.Add("appName", model.AppName);
            nvc.Add("senderId", model.SenderId);
            nvc.Add("AuthorizationToken", model.AuthorizationToken);
            nvc.Add("packageName", model.PackageName);
            nvc.Add("password", model.PassWord);
            nvc.Add("SandBoxPassWord", model.SandBoxPassWord);

            var path = Server.MapPath("~/tmpfile" + Guid.NewGuid());
            var sandboxpath = Server.MapPath("~/tmpfile" + Guid.NewGuid());
            Request.Files["certurl"].SaveAs(path);
            Request.Files["sandbox_certUrl"].SaveAs(sandboxpath);

            FileSendHelper.FileInfoCollection fic = new FileSendHelper.FileInfoCollection();
            fic.FileInfos.Add(new FileSendHelper.FileInfo(path, "certurl", "application/x-pkcs12"));
            fic.FileInfos.Add(new FileSendHelper.FileInfo(sandboxpath, "sandbox_certUrl", "application/x-pkcs12"));

            try
            {
                var resultStr = ApiHelper.HttpUploadMultiFile(url, nvc, fic);
                var result = JsonConvert.DeserializeObject<ApiResult>(resultStr);
                FileHelper.Delete(path, sandboxpath);
                if (result.status == 100) //成功
                {
                    AddSuccessInfo("操作成功");
                    return View();
                }
                AddErrorInfo("接口操作失敗,原因是：" + result.msg);
                return View(model);
            }
            catch (Exception ex)
            {
                AddErrorInfo("接口操作失敗,原因是：" + ex.Message);
                FileHelper.Delete(path, sandboxpath);
                return View(model);
            }
        }

        [HttpPost]
        public ActionResult AddMessage(AddMessageModel model)
        {
            Th.PageHeaderCrumbs = new List<string> { "發送推送消息", "Home", "推送到PushManager(新)" };

            if (!ModelState.IsValid || model == null)
            {
                AddErrorInfo();
                return View(model);
            }
            var url = "http://demo.comm01.com/pushmanager/message/add";
            var dict = new Dictionary<string, object>();
            dict.Add("appname", model.appname);
            dict.Add("message", model.message);
            dict.Add("data", model.data);

            dict.Add("googleList", model.googleList);
            dict.Add("notGoogleList", model.notGoogleList);
            dict.Add("IosList", model.IosList);

            try
            {
                var str = ApiHelper.SendPost(url, dict);
                var result = JsonConvert.DeserializeObject<ApiResult>(str);

                if (result.status == 100)
                {
                    AddSuccessInfo("操作成功");
                    return View(model);
                }

                AddErrorInfo("操作失敗，接口返回消息如下：" + result.msg);
                return View(model);
                //System.IO.File.Delete(path);
            }
            catch (Exception ex)
            {
                AddErrorInfo("接口操作失敗,原因是：" + ex.Message);
                return View(model);
            }
        }

        [HttpPost]
        public ActionResult AddProject2(AddProjectModel model)
        {
            var viewName = "AddProject";
            ViewBag.isNew = false;
            Th.PageHeaderCrumbs = new List<string> { "添加項目信息", "Home", "推送到AppMsgPush(舊)" };
            if (!ModelState.IsValid || model == null)
            {
                ViewBag.HasModelError = true;
                return View("AddProject", model);
            }
            HttpPostedFileBase file = null;
            var resultStr = string.Empty;
            if (Request.Files.Count > 0)
            {
                file = Request.Files[0];
            }
            var url = "http://demo.comm01.com/AppMsgPush/addapp.ashx";

            var nvc = new NameValueCollection();
            nvc.Add("appName", model.AppName);
            nvc.Add("senderId", model.SenderId);
            nvc.Add("AuthorizationToken", model.AuthorizationToken);
            nvc.Add("packageName", model.PackageName);
            nvc.Add("password", model.PassWord);
            var path = Server.MapPath("~/tmpfile" + Guid.NewGuid());
            if (file != null)
            {
                file.SaveAs(path);
                resultStr = ApiHelper.HttpUploadFile(url, path, "file", "application/x-pkcs12", nvc);
            }
            else
            {
                resultStr = ApiHelper.SendPost(url, nvc);
            }

            try
            {
                var result = JsonConvert.DeserializeObject<ApiResult2>(resultStr);

                if (result.Status == 1) //成功
                {
                    AddSuccessInfo("操作成功");
                    return View(viewName);
                }
                AddErrorInfo("接口操作失敗,原因是：" + result.Msg);
                return View(viewName, model);
                //System.IO.File.Delete(path);
            }
            catch (Exception ex)
            {
                AddErrorInfo("接口操作失敗,原因是：" + ex.Message);
                return View(viewName, model);
            }
        }

        [HttpPost]
        public ActionResult AddMessage2(AddMessageModel2 model)
        {
            Th.PageHeaderCrumbs = new List<string> { "發送推送消息", "Home", "推送到AppMsgPush(舊)" };
            if (!ModelState.IsValid || model == null)
            {
                ViewBag.HasModelError = true;
                return View(model);
            }
            var url = "http://demo.comm01.com/AppMsgPush/AddMessage.ashx";
            var dict = new Dictionary<string, object>();
            dict.Add("appname", model.appname);
            dict.Add("message", model.message);
            dict.Add("data", model.data);

            dict.Add("aztokenList", model.aztokenList);
            dict.Add("IosList", model.IosList);

            try
            {
                var str = ApiHelper.SendPost(url, dict);
                var result = JsonConvert.DeserializeObject<ApiResult2>(str);

                if (result.Status == 1) //成功
                {
                    AddSuccessInfo("操作成功");
                    return View();
                }
                AddErrorInfo("接口操作失敗,原因是：" + result.Msg);
                return View(model);
                //System.IO.File.Delete(path);
            }
            catch (Exception ex)
            {
                AddErrorInfo("接口操作失敗,原因是：" + ex.Message);
                return View(model);
            }
        }

        public class ApiResult
        {
            public int status { get; set; }
            public string msg { get; set; }
            public object data { get; set; }
        }

        //todo 忽略大小寫
        public class ApiResult2
        {
            public int Status { get; set; }
            public string Msg { get; set; }
            public object Data { get; set; }
        }
    }
}